<!--
  * 陈玉强
  *
  * @Author:    陈玉强
  * @Date:      2025-10-20 00:17:05
  * @Copyright  1
-->
<template>
  <a-modal
      :title="form.id ? '编辑 Syslog 配置' : '添加 Syslog 配置'"
      :width="800"
      :open="visibleFlag"
      @cancel="onClose"
      :maskClosable="false"
      :destroyOnClose="true"
      :bodyStyle="{ padding: '24px' }"
  >
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <!-- 基本信息 -->
      <a-divider orientation="left" style="margin: 16px 0 24px 0; font-weight: 600; color: #1890ff;">
        <template #title>
          <a-icon type="setting" style="margin-right: 8px;" />
          基本信息
        </template>
      </a-divider>
      
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="配置名称" name="name">
            <a-input v-model:value="form.name" placeholder="请输入配置名称" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="协议类型" name="protocolType">
            <a-select v-model:value="form.protocolType" placeholder="请选择协议类型" style="width: 100%">
              <a-select-option v-for="item in dictStore.getDictData(DICT_CODE_ENUM.syslog_protocol)" :key="item.dataValue" :value="item.dataValue">
                {{ item.dataLabel }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 服务器配置 -->
      <a-divider orientation="left" style="margin: 24px 0 16px 0; font-weight: 600; color: #1890ff;">
        <template #title>
          <a-icon type="server" style="margin-right: 8px;" />
          服务器配置
        </template>
      </a-divider>
      
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="服务器 IP" name="syslogServerIp">
            <a-input v-model:value="form.syslogServerIp" placeholder="请输入服务器 IP 地址" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="服务器端口" name="syslogServerPort">
            <a-input-number 
              v-model:value="form.syslogServerPort" 
              placeholder="请输入端口号" 
              :min="1" 
              :max="65535"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        
        <a-col :span="12">
          <a-form-item label="Topic" name="topic">
            <a-input v-model:value="form.topic" placeholder="请输入 Topic" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="密码" name="password">
            <a-input-password v-model:value="form.password" placeholder="请输入密码" allow-clear />
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 状态配置 -->
      <a-divider orientation="left" style="margin: 24px 0 16px 0; font-weight: 600; color: #1890ff;">
        <template #title>
          <a-icon type="control" style="margin-right: 8px;" />
          状态配置
        </template>
      </a-divider>
      
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="启用状态" name="forwardEnabled">
            <a-select v-model:value="form.forwardEnabled" placeholder="请选择启用状态" style="width: 100%">
              <a-select-option v-for="item in dictStore.getDictData(DICT_CODE_ENUM.syslog_status)" :key="item.dataValue" :value="item.dataValue">
                {{ item.dataLabel }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="加密状态" name="tlsEnabled">
            <a-select v-model:value="form.tlsEnabled" placeholder="请选择加密状态" style="width: 100%">
              <a-select-option v-for="item in dictStore.getDictData(DICT_CODE_ENUM.tls_status)" :key="item.dataValue" :value="item.dataValue">
                {{ item.dataLabel }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 统计信息 -->
      <a-divider orientation="left" style="margin: 24px 0 16px 0; font-weight: 600; color: #1890ff;">
        <template #title>
          <a-icon type="bar-chart" style="margin-right: 8px;" />
          统计信息
        </template>
      </a-divider>
      
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="发生数量" name="logCount">
            <a-input-number 
              v-model:value="form.logCount" 
              placeholder="请输入发生数量" 
              :min="0"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="备注" name="remark">
            <a-input v-model:value="form.remark" placeholder="请输入备注信息" allow-clear />
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 系统信息（仅编辑时显示） -->
      <template v-if="form.id">
        <a-divider orientation="left" style="margin: 24px 0 16px 0; font-weight: 600; color: #1890ff;">
          <template #title>
            <a-icon type="info-circle" style="margin-right: 8px;" />
            系统信息
          </template>
        </a-divider>
        
        <!-- <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="创建时间" name="createTime">
              <a-date-picker 
                show-time 
                valueFormat="YYYY-MM-DD HH:mm:ss" 
                v-model:value="form.createTime" 
                style="width: 100%" 
                placeholder="选择创建时间"
                disabled
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="修改时间" name="updateTime">
              <a-date-picker 
                show-time 
                valueFormat="YYYY-MM-DD HH:mm:ss" 
                v-model:value="form.updateTime" 
                style="width: 100%" 
                placeholder="选择修改时间"
                disabled
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="创建用户" name="createUser">
              <a-input v-model:value="form.createUser" placeholder="创建用户" disabled />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="修改用户" name="updateUser">
              <a-input v-model:value="form.updateUser" placeholder="修改用户" disabled />
            </a-form-item>
          </a-col>
        </a-row> -->
      </template>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="onClose" size="large">取消</a-button>
        <a-button type="primary" @click="onSubmit" size="large" :loading="loading">
          <template #icon>
            <a-icon type="save" />
          </template>
          {{ form.id ? '更新' : '保存' }}
        </a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup>
  import { reactive, ref, nextTick } from 'vue';
  import _ from 'lodash';
  import { message } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { syslogConfigApi } from '/@/api/business/syslog-config/syslog-config-api';
  import { smartSentry } from '/@/lib/smart-sentry';
  import { useDictStore } from '/@/store/modules/system/dict.js';
  import { DICT_CODE_ENUM } from '/@/constants/support/dict-const.js';

  // ------------------------ 字典数据 ------------------------
  const dictStore = useDictStore();

  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['reloadList']);

  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示
  const visibleFlag = ref(false);
  // 加载状态
  const loading = ref(false);

  function show(rowData) {
    Object.assign(form, formDefault);
    if (rowData && !_.isEmpty(rowData)) {
      Object.assign(form, rowData);
    }
    // 使用字典时把下面这注释修改成自己的字典字段 有多个字典字段就复制多份同理修改 不然打开表单时不显示字典初始值
    // if (form.status && form.status.length > 0) {
    //   form.status = form.status.map((e) => e.valueCode);
    // }
    visibleFlag.value = true;
    nextTick(() => {
      formRef.value.clearValidate();
    });
  }

  function onClose() {
    Object.assign(form, formDefault);
    visibleFlag.value = false;
  }

  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref();

  const formDefault = {
      id: undefined, // 主键ID，用于区分新增/编辑
      name: undefined, //名称
      syslogServerIp: undefined, //服务器ip
      syslogServerPort: undefined, //服务器端口
      protocolType: '', //协议类型 - 字符串类型匹配字典数据
      forwardEnabled: '', //启用状态 - 字符串类型匹配字典数据
      tlsEnabled: '', //加密状态 - 字符串类型匹配字典数据
      topic: undefined, //topic
      password: undefined, //密码
      remark: undefined, //备注
      logCount: undefined, //发生数量
      createTime: undefined, //创建时间
      updateTime: undefined, //修改时间
      createUser: undefined, //创建用户
      updateUser: undefined, //修改用户
  };

  let form = reactive({ ...formDefault });

  const rules = {
      name: [
        { required: true, message: '请输入配置名称', trigger: 'blur' },
        { min: 2, max: 50, message: '配置名称长度应在2-50个字符之间', trigger: 'blur' }
      ],
      syslogServerIp: [
        { required: true, message: '请输入服务器IP地址', trigger: 'blur' },
        { 
          pattern: /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/, 
          message: '请输入正确的IP地址格式', 
          trigger: 'blur' 
        }
      ],
      
      protocolType: [{ required: true, message: '请选择协议类型', trigger: 'change' }],
      forwardEnabled: [{ required: true, message: '请选择启用状态', trigger: 'change' }],
      tlsEnabled: [{ required: true, message: '请选择加密状态', trigger: 'change' }],
      
     
    
     
      // 系统信息字段在编辑时不需要验证，因为是只读的
      createTime: [],
      updateTime: [],
      createUser: [],
      updateUser: [],
  };

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields();
      await save();
    } catch (err) {
      if (err.errorFields) {
        message.error('请检查表单填写是否正确');
      }
    }
  }

  // 新建、编辑API
  async function save() {
    loading.value = true;
    try {
      // 确保数字类型字段正确转换
      const formData = {
        ...form,
        syslogServerPort: form.syslogServerPort ? Number(form.syslogServerPort) : form.syslogServerPort,
        logCount: form.logCount ? Number(form.logCount) : form.logCount
      };
      
      if (form.id) {
        await syslogConfigApi.update(formData);
        message.success('更新成功');
      } else {
        await syslogConfigApi.add(formData);
        message.success('添加成功');
      }
      emits('reloadList');
      onClose();
    } catch (err) {
      smartSentry.captureError(err);
      message.error(form.id ? '更新失败' : '添加失败');
    } finally {
      loading.value = false;
    }
  }

  defineExpose({
    show,
  });
</script>
